$(function () {
    // 点击按钮的时候; 
    // 1. 渲染页面; 
    // 2. 渲染分页; 

    var container = $(".container-goods");
    var pagination = $("#pagination");
    var token = getCookie("token")

    function init() {
        let res = $.ajax({
            url: "http://127.0.0.1:8888/goods/list",
            data: { current: 3, pagesize: 30 },
            dataType: "json"
        })
            .then(function (res) {
                // 让功能函数(自己写的函数)完成页面渲染; 
                renderPage(res);
                renderBullets(res);
            })
    }
    function renderPage(res) {
        container.html(res.list.map(item => `<div class="goods">
                        <img src="${item.img_big_logo}" alt="">
                        <h1>${item.title}</h1>
                        <h2>${item.price}</h2>
                        <p><button data-id = ${item.goods_id} class = "btn btn-danger btn-small">加入购物车</button></p>
                  </div>`).join(""))
    }

    function renderBullets(res) {
        $("#pagination").pagination({
            pageCount: res.total,
            callback: async function (instance) {
                // 自己写一下; 
                let res = $.ajax({
                    url: "http://127.0.0.1:8888/goods/list",
                    data: { current: instance.getCurrent(), pagesize: 30 },
                    dataType: "json"
                })
                    .done(function (res) {
                        renderPage(res);
                    })
            }
        });
    }
    $(".container-goods").on("click", ".btn", handlerAddCart)
    function handlerAddCart() {
        var user_id = getCookie("userid")
        var goods_id = $(this).attr("data-id")
        var options = {
            url: `http://127.0.0.1:8888/cart/add?id = ${user_id}&goodsId=${goods_id}`,
            type: "post",
            data: {
                id: user_id,
                goodsId: goods_id
            },
            headers: {
                authorization: token
            }
        }
        $.ajax(options)
            .then(function (data) {
                console.log(data);
                handlerAjax(data)
            })
    }
    function handlerAjax(data) {
        switch (data.code) {
            case 1:
                alert(data.message)
                break
            case 401:
                alert("抱歉您还没登录，请先登录后再加入购物车")
                location.href = "./login.html#goods"
                break
        }
    }
    init()
    initNav()
})